package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.dao.SysLogDao;
import com.cy.pj.sys.pojo.SysLog;
import com.cy.pj.sys.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//import com.google.protobuf.ServiceException;

//import com.google.protobuf.ServiceException;

//import com.google.protobuf.ServiceException;

@Service
public class SysLogServiceImpl implements SysLogService {
    @Autowired
    private SysLogDao sysLogDao;


    @Override
    public void saveObject(SysLog entity) {
        String tName = Thread.currentThread().getName();
        System.out.println("SysLogServiceImpl.saveObject->thread.name->"+tName);
        try {
           Thread.sleep(5000);
        }catch (Exception e){}
        sysLogDao.insertObject(entity);

    }

    @RequiredLog(value = "日志删除")
    @Override
    public int deleteObjects(Integer... ids) {
        //1.判定参数合法性
        if(ids==null||ids.length==0)
            throw new IllegalArgumentException("请选择一个");
        //2.执行删除操作
        int rows;
        try{
            rows=sysLogDao.deleteObjects(ids);
        }catch(Throwable e){
            e.printStackTrace();
            //发出报警信息(例如给运维人员发短信)
            throw new ServiceException("系统故障，正在恢复中...");
        }
        //4.对结果进行验证
        if(rows==0)
            throw new ServiceException("记录可能已经不存在");
        //5.返回结果
        return rows;
    }

    @RequiredLog(value = "日志查询")
    @Override
    public PageObject<SysLog> findPageObjects(String username, Integer pageCurrent)  {
        if(pageCurrent==null || pageCurrent<1)throw new IllegalArgumentException("当前页码不正确");
        int rowCount= sysLogDao.getRowCount(username);
        if(rowCount==0) throw new ServiceException("系统没有找到对应记录");
        int pageSize = 5;
        int startIndex = (pageCurrent-1)*pageSize;
        List<SysLog> records = sysLogDao.findPageObjects(username,startIndex,pageSize);
        /*
        PageObject<SysLog> pageObject=new PageObject<>();
        //4.2)封装数据
        pageObject.setPageCurrent(pageCurrent);
        pageObject.setPageSize(pageSize);
        pageObject.setRowCount(rowCount);
        pageObject.setRecords(records);
        pageObject.setPageCount((rowCount-1)/pageSize+1);

        */
        //5.返回封装结果。
        //return pageObject;
        return new PageObject<>(rowCount,records,pageCurrent,pageSize);

    }
}
